﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HelfenHelfen.Logic.Factories;
using System.Web.Security;
using HelfenHelfen.DataAccess.Entities;
using HelfenHelfen.Web.Forms.Site.Services;

namespace HelfenHelfen.Web.Forms.Site
{
    public partial class Messages : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var logic = LogicFactory.CreateMessageLogic();
            var userLogic = LogicFactory.CreateUserDetailLogic();

            var user = Membership.GetUser();
            if (user != null)
            {
                var result = logic.GetMessagesForUser(
                    (Guid)user.ProviderUserKey)
                    .Select(m => new MessageViewModel()
                    {
                        Title = m.Title,
                        Message = m.Message1,
                        MessageGUID = m.MessageGUID,
                        Sender = ConvertToUserViewModel(userLogic, m.SenderUserDetailGUID)
                    });

                this.MessageListView.DataSource = result;
                this.MessageListView.DataBind();
            }
        }


        private UserDetailViewModel ConvertToUserViewModel(Interfaces.IUserDetailLogic userLogic, Guid userGuid)
        {
            var user = userLogic.GetUserDetailByGuid(userGuid);
            return new UserDetailViewModel()
            {
                FirstName = user.FirstName,
                LastName = user.Lastname,
                UserDetailGUID = user.UserDetailGUID
            };
        }

        protected void SendButton_Click(object sender, EventArgs e)
        {
            var logic = LogicFactory.CreateMessageLogic();

            Message msg = new Message()
            {
                Title = txtTitle.Text,
                Message1 = txtMessage.Text,
                MessageGUID = Guid.NewGuid(),
                CreationDateTime = DateTime.Now
            };
            msg.SenderUserDetailGUID = (Guid)Membership.GetUser().ProviderUserKey;
            msg.RecipientUserDetailGUID = msg.SenderUserDetailGUID;

            logic.SendMessage(msg);
        }

        protected void MessageListView_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                var list = new List<MessageViewModel>(((IEnumerable<MessageViewModel>)this.MessageListView.DataSource));

                var msg = list[e.Item.DataItemIndex];
                
                var logic = LogicFactory.CreateMessageLogic();
                logic.DeleteMessage(msg.MessageGUID);
            }
        }

        protected void MessageListView_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            
        }
    }
}